<template>
  <div
    class="videoWrapper"
    :style="{ width: width, height: height }"
    @mouseover="showBottomTool = true"
    @mouseleave="showBottomTool = false"
  >
    <video
      loop
      :muted="isMuted"
      id="myVideo"
      width="640"
      height="360"
      :controls="false"
      ref="videoRef"
      @play="updateVideoStatus"
      @pause="updateVideoStatus"
      @ended="updateVideoStatus"
    >
      <!-- <source v-if="moment.videoUrl == ''" src="@/assets/mp4/动漫剪辑.mp4" type="video/mp4" /> -->
      <source :src="moment.video" type="video/mp4" />
    </video>
    <div class="videoTool" v-if="!isPaused && isEnd" @click="play">
      <PlayCircleOutlined />
    </div>
    <div class="videoTool" v-if="isPaused && !isEnd" @click="play">
      <PauseCircleOutlined />
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  SoundOutlined,
  ExpandOutlined
} from '@ant-design/icons-vue'
import { ref, inject, defineProps, onMounted, computed } from 'vue'
const isPaused = ref<Boolean>(false) //暂停状态
const isEnd = ref<Boolean>(true) // 停止状态
const isMuted = ref<Boolean>(false) //是否静音
const videoRef = ref()
const observer = ref()
const showBottomTool = ref<Boolean>(true)

const props = defineProps({
  width: {
    type: String,
    default: '250px'
  },
  height: {
    type: String,
    default: '325px'
  }
})
const moment = inject('moment', {})
// 播放暂停功能
const play = () => {
  if (videoRef.value.paused || videoRef.value.ended) {
    videoRef.value.play()
  } else {
    videoRef.value.pause()
  }
}
const updateVideoStatus = () => {
  isPaused.value = videoRef.value.paused
  isEnd.value = videoRef.value.ended
}
const setupIntersectionObserver = () => {
  observer.value = new IntersectionObserver(
    (entries) => {
      const entry = entries[0]
      if (!entry.isIntersecting) {
        // 消失在视窗
        videoRef.value.pause()
      } else {
        videoRef.value.play()
      }
    },
    {
      root: null, //默认为视窗
      rootMargin: '0px',
      threshold: [0, 1] // 当元素0%或100%可见时触发回调
    }
  )
  observer.value.observe(videoRef.value)
}
onMounted(() => {
  setupIntersectionObserver()
})
// todo 如果video消失在视窗之内就暂停播放
</script>
<style lang="less" scoped>
.videoWrapper {
  background-color: #000;
  position: relative;
  .videoTool {
    background-color: #0006;
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
    color: #868686;
  }
  #myVideo {
    height: 100%;
    width: 100%;
  }
  .bottomTool {
    background-color: #292929;
    position: absolute;
    height: 30px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
    padding: 0 5%;
    color: white;
    bottom: 0;
    div {
      display: flex;
      gap: 15px;
    }
  }
}
</style>
